package com.jule.teenpatti.game.play.impl;

import com.jule.teenpatti.base.enums.GameConst;
import com.jule.teenpatti.game.gameUtil.GameLogic;
import com.jule.teenpatti.game.model.eenum.NextBetPlayerReasonEnum;
import com.jule.teenpatti.game.play.AbstractTable;
import com.jule.teenpatti.game.service.TableService;
import com.jule.teenpatti.game.service.TimerService;
import com.jule.teenpatti.log.service.LogReasons;
import com.jule.teenpatti.game.model.CardConstent;
import com.jule.teenpatti.game.model.PlayerInfo;
import com.jule.teenpatti.game.model.eenum.PlayTypeEnum;
import com.jule.teenpatti.game.model.eenum.PlayerStateEnum;
import com.jule.teenpatti.base.enums.TableStateEnum;
import com.jule.teenpatti.game.utils.log.TableLogUtil;
import com.jule.teenpatti.game.vavle.notice.NoticeBroadcastMessages;

public class DealerTable  extends AbstractTable {

    public DealerTable(String gameId, String roomId, String tableId) {
        super(gameId, roomId, tableId);
    }

    @Override
    public int giveCardCounts() {
        log.debug("-----------------------------------------dealerPlayType: "+this.dealerPlayType);
        if(this.dealerPlayType == PlayTypeEnum.Joker.getGameId()){
            return CardConstent.JOKER_HAND_CARDS;
        }
        return CardConstent.HAND_CARDS;
    }

    /**
     * 获得下一个行动的玩家
     *
     * @param preBetSeatNum
     * @return
     */
    @Override
    public PlayerInfo getNextBetPlayer(int preBetSeatNum, NextBetPlayerReasonEnum reasonEnum) {
        PlayerInfo nextBetPlayer = null;
        if (this.getInGamePlayers().size() <= GameConst.FINAL_PLAYER_NUM) {
            return null;
        }
        //计算下一个下注玩家的座位号
        int nextBetSeatNum = preBetSeatNum;
        while (true) {
            nextBetSeatNum -= 1;
            if (nextBetSeatNum < 1) {
                nextBetSeatNum = 5;
            }
            //再次找到当前位置，说明已无合适下一个行动者，返回null
            if (nextBetSeatNum == preBetSeatNum) {
                return null;
            }
            //如果当前行动者的下家是庄家，则轮次加1
            if (nextBetSeatNum == this.firstBetSeatNum) {
                if(this.currRoundId == this.getRoomConfig().getMaxBlindRound()){
                    return null;
                }
                this.currRoundId += 1;
            }
            if (this.getInGamePlayers().containsKey(nextBetSeatNum)) {
                nextBetPlayer = this.getInGamePlayers().get(nextBetSeatNum);
                if (nextBetPlayer.getState() != PlayerStateEnum.fold && nextBetPlayer.getState() != PlayerStateEnum.showfail) {
                    //找到了合适的下一个行动者，结束循环
                    break;
                }
            }
        }
        //将下一个行动玩家，设置为牌桌当前行动玩家
        if (null != nextBetPlayer){
            setCurrActionPlayerId(nextBetPlayer.getPlayerId());
            setCurrActionSeatNum(nextBetPlayer.getSeatNum());
        }
        return nextBetPlayer;
    }

    @Override
    public void initTableStateAttribute() {
        super.initTableStateAttribute();
    }

    @Override
    public double playerDataSettlement(PlayerInfo player) {
        double currentMoney = super.playerDataSettlement(player);
        if(getTableStateEnum() == TableStateEnum.choosePlayType){
            if(getInGamePlayers().size() >= 2){
                if(player.getSeatNum() == getCurrDealerSeatNum()){
                    //自动选择上局玩法，没有则为classic
                    setDealerPlayType(getDealerPlayType() != 0 ? getDealerPlayType() : PlayTypeEnum.classic.getGameId());
                    choosePlayType(true);
                }
            }else{
                TimerService.getInstance().delTimerTask(getRoomTableRelation());
                setTableStateEnum(TableStateEnum.IDEL);
                setTableStatus();
            }
        }
        return currentMoney;
    }

    @Override
    public void choosePlayType(boolean none){

        if (getInGamePlayers().size() <= GameConst.FINAL_PLAYER_NUM) { //初始化桌内
            //当牌桌只剩一个玩家时，修改玩家状态为初始坐下状态
            if (getInGamePlayersBySeatNum().size() <= GameConst.FINAL_PLAYER_NUM) {
                TableService.getInstance().updateInGamePlayersBySeatNumPlayerStateSiteDown(this);
            }
            for (PlayerInfo player : getInGamePlayersBySeatNum().values()) { //更新所有玩家状态为准备
                //重置玩家游戏数据
                player.resetGameingInfo();
            }
            //修改桌子的状态
            setTableStateEnum(TableStateEnum.IDEL);
            setTableStatus();
            initTableStateAttribute();
            return ;
        }

        //广播玩家选定的玩法
        try {
            NoticeBroadcastMessages.selectedPlayType(this,none);
        }catch (Exception e){
            log.debug("桌子对象为null");
        }
        double firstBetScore = getBaseBetScore() / 2;
        for(PlayerInfo playerInfo : getInGamePlayers().values()){
            getAlreadyBet().put(playerInfo.getPlayerId(),firstBetScore);
            playerInfo.setState(PlayerStateEnum.gameing); //修改所有玩家的状态为游戏中
            playerInfo.minusPlayScoreStore(firstBetScore, LogReasons.CommonLogReason.GAME_GIVECARD);
            TableLogUtil.gameAnte(0,"gameStart_ant",playerInfo.getPlayerId(),playerInfo.getNickName(),
                    getPlayType()+"",getRoomId(),getTableId(),getCurrGameOrderId(),
                    firstBetScore);
            playerInfo.setCurChipsLose(firstBetScore);
            //发送通知
            NoticeBroadcastMessages.moneyChangeNotice(this,playerInfo.getPlayerId(),playerInfo.getPlayScoreStore());
        }
        setTotalAlreadyBet(firstBetScore * getInGamePlayersBySeatNum().size());

        PlayerInfo nextBetPlayer = getNextBetPlayer(getCurrDealerSeatNum(),NextBetPlayerReasonEnum.DEALER);
        if (nextBetPlayer != null) {
            setFirstBetSeatNum(nextBetPlayer.getSeatNum());
            nextBetPlayer.setState(PlayerStateEnum.beting);
        }
        setTableStateEnum(TableStateEnum.BET); //修改牌桌状态为下注中
        setTableStatus();

        try {
            //调用计时器来播放动画(多少人多少秒) todo 待补充
            NoticeBroadcastMessages.giveCardRoundStart(this, nextBetPlayer);
            //玩法要求：hukam
            if (currPlayType() == PlayTypeEnum.hukam.getValue()) {
                //广播此局游戏的癞子牌
                NoticeBroadcastMessages.mixedCard(this);
            }
        } catch (Exception ex) {
            log.error("Send notice ERROR:" + ex.getMessage());
        }
        //第一次下注延时(发牌)
        GameLogic.commonTimer(this,getInGamePlayers().size(), true);
    }

    @Override
    public int currPlayType() {
        return dealerPlayType;
    }

}
